package com.travelsky.flash.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.travelsky.flash.util.log.FlashLogger;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.SCPClient;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.StreamGobbler;
 
/**
 * Provides static methods for running SSH, scp as well as local commands.
 *
 */
public class SSHExecUtil {
 
	private static FlashLogger logger = new FlashLogger(SSHExecUtil.class);

 
 /**
  * Get remote file through scp
   * @param host
   * @param username
   * @param password
   * @param remoteFile
   * @param localDir
   * @throws IOException
   */
 public static void scpGet(String host, String username, String password,
      String remoteFile, String localDir) throws IOException {
	 
    logger.info("spc [" + remoteFile + "] from " + host + " to " + localDir);
    Connection conn = getOpenedConnection(host, username, password);
    SCPClient client = new SCPClient(conn);
    client.get(remoteFile, localDir);
    conn.close();
 }
 
 /**
   * Put local file to remote machine.
   * @param host
   * @param username
   * @param password
   * @param localFile
   * @param remoteDir
  * @throws IOException
   */
 public static void scpPut(String host, String username, String password,
      String localFile, String remoteDir) throws IOException {
    logger.info("spc [" + localFile + "] to " + host + remoteDir);
    Connection conn = getOpenedConnection(host, username, password);
    SCPClient client = new SCPClient(conn);
    client.put(localFile, remoteDir);
    conn.close();
 }
 
 /**
   * Run SSH command.
   * @param host
   * @param username
   * @param password
   * @param cmd
   * @return exit status
   * @throws IOException
   */
 public static int runSSH(String host, String username, String password,
      String cmd) throws IOException {
    logger.info("running SSH cmd [" + cmd + "]");
 
    Connection conn = getOpenedConnection(host, username, password);
    Session sess = conn.openSession();
    sess.execCommand(cmd);
 
    InputStream stdout = new StreamGobbler(sess.getStdout());
    BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
 
    while (true) {
      // attention: do not comment this block, or you will hit NullPointerException
      // when you are trying to read exit status
      String line = br.readLine();
      if (line == null)
        break;
      logger.info(line);
    }
 
    sess.close();
    conn.close();
    if(null == sess.getExitStatus() || (null != sess.getExitStatus() && sess.getExitStatus()==0)) {
    	// 执行成功
    	logger.info("SSH exec Success.");
    	return 1;
    	
    } else {
    	logger.info("SSH exec Fail.");
    	return -1;
    }
    
 }
 
 /**
  * Run SSH command.
  * @param host
  * @param username
  * @param password
  * @param cmd
  * @return exit status
  * @throws IOException
  */
/*public static int loginCallScpPut(String fromhost, String fromUsr, String fromPwd,String fromFile,
     String tohost,String toUsr,String toPwd,String remoteDir) throws IOException {
   if (logger.isDebugEnabled()) {
     logger.debug("running SCP from to");
   }
   Connection connfrom = getOpenedConnection(fromhost, fromUsr, fromPwd);
   Session sess = connfrom.openSession();
   Connection connto = getOpenedConnection(tohost, toUsr, toPwd);
   SCPClient client = new SCPClient(connto);
   client.put(fromFile, remoteDir);
   //scpPut(tohost, toUsr, toPwd, localFile, remoteDir);

   InputStream stdout = new StreamGobbler(sess.getStdout());
   BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

   while (true) {
     // attention: do not comment this block, or you will hit NullPointerException
     // when you are trying to read exit status
     String line = br.readLine();
     if (line == null)
       break;
     if (logger.isDebugEnabled()) {
       logger.debug(line);
     }
   }

   sess.close();
   connto.close();
   connfrom.close();
   return sess.getExitStatus().intValue();
}*/
 
 /**
   * return a opened Connection
   * @param host
   * @param username
   * @param password
   * @return
   * @throws IOException
   */
 private static Connection getOpenedConnection(String host, String username,
      String password) throws IOException {
    logger.info("connecting to " + host + " with user xxxxxx"
          + " and pwd ******");
 
    Connection conn = new Connection(host);
    conn.connect(); // make sure the connection is opened
    boolean isAuthenticated = conn.authenticateWithPassword(username,
        password);
    if (isAuthenticated == false)
      throw new IOException("Authentication failed.");
    return conn;
 }
 
 /**
   * Run local command
   * @param cmd
   * @return exit status
   * @throws IOException
   */
 public static int runLocal(String cmd) throws IOException {
    logger.info("running local cmd [" + cmd + "]");
 
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec(cmd);
 
    InputStream stdout = new StreamGobbler(p.getInputStream());
    BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
 
    while (true) {
      String line = br.readLine();
      if (line == null)
        break;
      logger.info(line);
 
    }
    return p.exitValue();
 }
}
